from pydantic import BaseModel, Field
from typing import Dict, Any, Optional, List, Generic, TypeVar
from enum import Enum
from datetime import datetime

T = TypeVar('T')

class SecurityLevel(str, Enum):
    """安全等级枚举"""
    LOW = "low"      # 低安全等级 - 使用exec执行器
    HIGH = "high"    # 高安全等级 - 使用完全隔离容器

class CodeType(str, Enum):
    """代码类型枚举"""
    PYTHON = "python"
    JAVASCRIPT = "javascript"
    BASH = "bash"
    JAVA = "javas"
    # TODO: 编译型语言

class TaskStatus(str, Enum):
    """任务状态枚举"""
    PENDING = "pending"
    RUNNING = "running"
    COMPLETED = "completed"
    FAILED = "failed"
    TIMEOUT = "timeout"

class UserInfo(BaseModel):
    """用户信息"""
    user_id: str = Field(..., description="用户ID")
    username: str = Field(..., description="用户名")
    permissions: List[str] = Field(default=[], description="用户权限列表")
    
class CodeExecutionRequest(BaseModel):
    """代码执行请求"""
    code: str = Field(..., description="要执行的代码文本")
    code_type: CodeType = Field(..., description="代码类型")
    user_info: UserInfo = Field(..., description="用户信息")
    security_level: SecurityLevel = Field(..., description="安全等级")
    timeout_seconds: int = Field(default=30, ge=1, le=300, description="超时时间（秒）")
    memory_limit_mb: int = Field(default=128, ge=16, le=1024, description="内存限制（MB）")
    cpu_limit: float = Field(default=0.5, ge=0.1, le=2.0, description="CPU限制（核数）")
    environment_vars: Dict[str, str] = Field(default={}, description="环境变量")
    input_arg: Dict[str, Any] = Field(default={}, description="传递给main函数的输入参数")
    
class ExecutionResult(BaseModel):
    """执行结果"""
    task_id: str = Field(..., description="任务ID")
    status: TaskStatus = Field(..., description="执行状态")
    output: Optional[str] = Field(None, description="标准输出")
    error: Optional[str] = Field(None, description="错误输出")
    return_code: Optional[int] = Field(None, description="返回码")
    execution_time: Optional[float] = Field(None, description="执行时间（秒）")
    memory_usage: Optional[int] = Field(None, description="内存使用（MB）")
    cpu_usage: Optional[float] = Field(None, description="CPU使用率")
    start_time: Optional[datetime] = Field(None, description="开始时间")
    end_time: Optional[datetime] = Field(None, description="结束时间")
    
class QueueTask(BaseModel, Generic[T]):
    """队列任务泛型类"""
    task_id: str = Field(..., description="任务ID")
    payload: T = Field(..., description="任务负载")
    priority: int = Field(default=0, description="优先级，数字越大优先级越高")
    created_at: datetime = Field(default_factory=datetime.utcnow, description="创建时间")
    max_retries: int = Field(default=3, description="最大重试次数")
    retry_count: int = Field(default=0, description="当前重试次数")
    
class ExecutorConfig(BaseModel):
    """执行器配置"""
    max_concurrent_tasks: int = Field(default=5, ge=1, le=100, description="最大并发任务数")
    default_timeout: int = Field(default=30, ge=1, le=300, description="默认超时时间")
    resource_limits: Dict[str, Any] = Field(default={}, description="资源限制配置")
    
class ApiResponse(BaseModel, Generic[T]):
    """API响应泛型类"""
    success: bool = Field(..., description="是否成功")
    message: str = Field(..., description="响应消息")
    data: Optional[T] = Field(None, description="响应数据")
    timestamp: datetime = Field(default_factory=datetime.utcnow, description="响应时间")
    
class TaskSubmissionResponse(BaseModel):
    """任务提交响应"""
    task_id: str = Field(..., description="任务ID")
    estimated_wait_time: Optional[int] = Field(None, description="预估等待时间（秒）")
    queue_position: Optional[int] = Field(None, description="队列位置") 